package com.smasher.bluetooth.scan;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;

import java.util.Set;

public abstract class BaseDiscovering implements ScanDelegate, Handler.Callback {

    public static final String TAG = "BaseDiscovering";

    protected final BluetoothManager bluetoothManager;
    protected final BluetoothAdapter bluetoothAdapter;

    protected DeviceFoundListener mDeviceFoundListener;

    protected Handler mHandler = new Handler(Looper.getMainLooper(), this);


    public BaseDiscovering(Context context) {
        bluetoothManager = context.getSystemService(BluetoothManager.class);
        //蓝牙适配器
        bluetoothAdapter = bluetoothManager.getAdapter();
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        return false;
    }

    public void setDeviceFoundListener(DeviceFoundListener listener) {
        mDeviceFoundListener = listener;
    }

    /**
     * 查询已配对设备
     */
    @RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_CONNECT})
    public Set<BluetoothDevice> queryRecord() {
        return bluetoothAdapter.getBondedDevices();
    }


    @RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT})
    public boolean enableBluetooth(Context context) {

        if (bluetoothAdapter.isEnabled()) {
            Toast.makeText(context, "蓝牙已开启", Toast.LENGTH_SHORT).show();
            return true;
        } else {
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S) {
                return bluetoothAdapter.enable();
            } else {
                Toast.makeText(context, "请开启蓝牙", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
    }


    public Intent createIntentForEnable() {
        return new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    }


    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    public void disableBluetooth(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            boolean result = bluetoothAdapter.disable();
            Log.e(TAG, "关闭蓝牙结果: " + result);
        }
    }

    @Override
    public void release(Context context) {
        mHandler.removeCallbacksAndMessages(null);
        mDeviceFoundListener = null;
    }
}
